package com.lychee.common.core.config;

import jakarta.servlet.DispatcherType;
import com.lychee.common.core.config.properties.XssProperties;
import com.lychee.common.core.filter.RepeatableFilter;
import com.lychee.common.core.filter.XssFilter;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

/**
 * Filter过滤器配置
 *
 * @author DingHao
 */
@AutoConfiguration
@EnableConfigurationProperties(XssProperties.class)
public class FilterConfig {

    @Bean
    //条件注解，只有配置文件中xss.enabled=true 时，xssFilterRegistration() 方法才会被调用，从而注册这个过滤器
    @ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
    public FilterRegistrationBean<XssFilter> xssFilterRegistration() {
        //Spring提供的工具类，专门用来在Servlet容器中注册自定义的Filter(过滤器)
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
        //设置过滤器的分派器类型
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        //设置要注册的具体过滤器实例
        registration.setFilter(new XssFilter());
        //定义这个过滤器拦截的 URL 路径模式
        registration.addUrlPatterns("/*");
        //为这个过滤器注册一个名称
        registration.setName("xssFilter");
        //设置这个过滤器的优先级，数字越小优先级越高
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE + 1);
        return registration;
    }

    @Bean
    public FilterRegistrationBean<RepeatableFilter> someFilterRegistration() {
        FilterRegistrationBean<RepeatableFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new RepeatableFilter());
        registration.addUrlPatterns("/*");
        registration.setName("repeatableFilter");
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        return registration;
    }

}
